package com.edu.hre.struts.action.recruit;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.edu.hre.common.email.EMailSender;
import com.edu.hre.common.encrypt.Encrypter;
import com.edu.hre.common.utils.BeanFinder;
import com.edu.hre.common.utils.ComboBoxInit;
import com.edu.hre.common.utils.CommonUtils;
import com.edu.hre.common.utils.StringConstants;
import com.edu.hre.db.pojo.HreCandidateEducation;
import com.edu.hre.db.pojo.HreCandidateLanguage;
import com.edu.hre.db.pojo.HreCandidateLicense;
import com.edu.hre.db.pojo.HreCandidateSkill;
import com.edu.hre.db.pojo.HreCandidateWorkExperience;
import com.edu.hre.db.pojo.HreEmpAttachment;
import com.edu.hre.db.pojo.HreEmpEducation;
import com.edu.hre.db.pojo.HreEmpLanguage;
import com.edu.hre.db.pojo.HreEmpLicense;
import com.edu.hre.db.pojo.HreEmpPicture;
import com.edu.hre.db.pojo.HreEmpSkill;
import com.edu.hre.db.pojo.HreEmpWorkExperience;
import com.edu.hre.db.pojo.HreEmployee;
import com.edu.hre.db.pojo.HreJobCandidate;
import com.edu.hre.db.pojo.HreJobCandidateAttachment;
import com.edu.hre.db.pojo.HreJobCandidatePicture;
import com.edu.hre.db.pojo.HreJobInterview;
import com.edu.hre.db.pojo.HreJobVacancy;
import com.edu.hre.db.pojo.HreUser;
import com.edu.hre.db.service.BaseService;
import com.edu.hre.db.sql.pim.EmployeeDAOService;
import com.edu.hre.db.utils.Compare;
import com.edu.hre.struts.form.recruit.EmployForm;

public class EmployAction extends Action {

	private static final Logger logger = Logger.getLogger(EmployAction.class);
	private static final BaseService baseService = BeanFinder.getBean(BaseService.BEAN_NAME, BaseService.class);
	private static final EMailSender emailSender = BeanFinder.getBean(EMailSender.BEAN_NAME, EMailSender.class);
	private static final EmployeeDAOService employeeDAOService = BeanFinder.getBean(EmployeeDAOService.BEAN_NAME, EmployeeDAOService.class);
	private final String ACTION_NAME = "employ";
	
	public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		CommonUtils.println(CommonUtils.getSourceCodeLocation());
		EmployForm beanForm = (EmployForm) form;
		
		if(request.getParameter("btnAgree") == null){

			int id = CommonUtils.getIntParameter("id", request);
			int intId = CommonUtils.getIntParameter("intId", request);
			beanForm.setCanId(id);
			beanForm.setIntId(intId);
			beanForm.setMessage(StringConstants.BLANK);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		String message = validateForm(beanForm);
		if(!StringUtils.isBlank(message)){
			beanForm.setMessage(message);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		HreJobCandidate tmp = baseService.getFirstPojo("id", Compare.EQUAL, beanForm.getCanId(), null, null, 0, HreJobCandidate.class);
		if (tmp == null) {
			initFormBean(beanForm);
			beanForm.setMessage(StringConstants.BLANK);
			return mapping.findForward(ACTION_NAME);
		}

		// Basic information.
		HreEmployee emp = new HreEmployee();
		emp.setEmpFirstname(tmp.getFirstName());
		emp.setEmpMiddleName(tmp.getMiddleName());
		emp.setEmpLastname(tmp.getLastName());
		emp.setEmpOthEmail(tmp.getEmail());
		emp.setEmpMobile(tmp.getContactNumber());
		emp.setEmpIdCardNum(tmp.getIdCardNumber());
		emp.setEmpIdCardDate(tmp.getIdCardDateIssued());
		emp.setEmpIdCardPlace(tmp.getIdCardLocationIssued());
		emp.setEmpGender(tmp.getGender() == null ? null : tmp.getGender().shortValue());
		emp.setEmpMaritalStatus(tmp.getMaritalStatus());
		emp.setNationCode(tmp.getNationality());
		emp.setEmpBirthday(tmp.getEmpBirthday());
		emp.setEmpStreet1(tmp.getAddress());
		emp.setDistrictCode(tmp.getDistrictCode());
		emp.setProvinCode(tmp.getProvinCode());
		emp.setIsDeleted(false);
		emp.setDateCreated(new Date());
		emp.setDateModified(new Date());

		boolean status = baseService.saveOrUpdate(emp);
		if (!status) {
			beanForm.setMessage(StringConstants.INSERT_FAILURE_MESSAGE);
			initFormBean(beanForm);
			return mapping.findForward(ACTION_NAME);
		}
		
		// Create new user.
		String newUsername = employeeDAOService.getNewUsername(
				CommonUtils.normalizeString(emp.getEmpFirstname()),
				CommonUtils.normalizeString(emp.getEmpMiddleName()),
				CommonUtils.normalizeString(emp.getEmpLastname()));

		HreUser user = new HreUser();
		user.setUserName(newUsername);
		user.setUserPassword(Encrypter.encodeMD5(beanForm.getPassword()));
		user.setUserRoleId(beanForm.getUserRole());
		user.setEmpNumber(emp.getEmpNumber());
		user.setDeleted(false);
		user.setStatus(true);
		user.setDateCreated(new Date());
		user.setDateModified(new Date());
		
		status = baseService.saveOrUpdate(user);
		if (status) {
			emp.setMainUsername(user.getUserName());
			status = baseService.saveOrUpdate(emp);
		}
		
		HreJobInterview tmpInt = baseService.getFirstPojo("id", Compare.EQUAL, beanForm.getIntId(), HreJobInterview.class);
		informHiringInformation(tmpInt, tmp, user, beanForm.getPassword());
		
		// Copy Image
		HreEmpPicture empPic = new HreEmpPicture();
		HreJobCandidatePicture canPic = baseService.getFirstPojo("candidateId", Compare.EQUAL, beanForm.getCanId(), null, null, 0, HreJobCandidatePicture.class);
		
		if (canPic != null) {
			empPic.setEmpNumber(emp.getEmpNumber());
			empPic.setEpicFileHeight(canPic.getCanFileHeight());
			empPic.setEpicFilename(canPic.getCanFileName());
			empPic.setEpicFileSize(canPic.getCanFileSize());
			empPic.setEpicFileWidth(canPic.getCanFileWidth());
			empPic.setEpicPicture(canPic.getCanPicture());
			empPic.setEpicType(canPic.getCanFileType());
			empPic.setDateCreated(new Date());
			empPic.setDateModified(new Date());
			
			status = baseService.saveOrUpdate(empPic);
		}

		// Copy CV
		HreEmpAttachment empAtt = new HreEmpAttachment();
		HreJobCandidateAttachment canAtt = baseService.getFirstPojo("candidateId", Compare.EQUAL, beanForm.getCanId(), null, null, 0, HreJobCandidateAttachment.class);
		
		if (canAtt != null) {
			empAtt.setEmpNumber(emp.getEmpNumber());
			empAtt.setEattachFilename(canAtt.getFileName());
			empAtt.setEattachAttachment(canAtt.getFileContent());
			empAtt.setEattachSize(canAtt.getFileSize());
			empAtt.setEattachType(canAtt.getFileType());
			
			status = baseService.saveOrUpdate(empAtt);
		}
		
		// Copy educations.
		List<HreCandidateEducation> canEdus = baseService.getPojos("candidateId", Compare.EQUAL, beanForm.getCanId(), null, null, -1, 0, HreCandidateEducation.class);
		if (canEdus != null && canEdus.size() > 0) {
			
			for (HreCandidateEducation canEdu: canEdus) {
				HreEmpEducation empEdu = new HreEmpEducation();
				empEdu.setEmpNumber(emp.getEmpNumber());
				empEdu.setEducationId(canEdu.getEducationId());
				empEdu.setMajor(canEdu.getMajorId());
				empEdu.setInstitute(canEdu.getInstitute());
				empEdu.setStartDate(canEdu.getStartDate());
				empEdu.setEndDate(canEdu.getEndDate());
				empEdu.setScore(canEdu.getScore());
				empEdu.setYear(canEdu.getYear());
				empEdu.setDateCreated(new Date());
				empEdu.setDateModified(new Date());
				
				status = baseService.saveOrUpdate(empEdu);
			}
		}
		
		// Copy skills.
		List<HreCandidateSkill> canSkills = baseService.getPojos("candidateId", Compare.EQUAL, beanForm.getCanId(), null, null, -1, 0, HreCandidateSkill.class);
		if (canSkills != null && canSkills.size() > 0) {
			
			for (HreCandidateSkill canSkill: canSkills) {
				HreEmpSkill empSkill = new HreEmpSkill();
				empSkill.setEmpNumber(emp.getEmpNumber());
				empSkill.setSkillId(canSkill.getSkillId());
				empSkill.setYearsOfExp(canSkill.getYearsOfExp());
				empSkill.setComments(canSkill.getComments());
				empSkill.setDateCreated(new Date());
				empSkill.setDateModified(new Date());
				
				status = baseService.saveOrUpdate(empSkill);
			}
		}
		
		// Copy languages.
		List<HreCandidateLanguage> canLangs = baseService.getPojos("candidateId", Compare.EQUAL, (long) beanForm.getCanId(), null, null, -1, 0, HreCandidateLanguage.class);
		if (canLangs != null && canLangs.size() > 0) {
			
			for (HreCandidateLanguage canLang: canLangs) {
				HreEmpLanguage empLang = new HreEmpLanguage();
				empLang.setEmpNumber(emp.getEmpNumber());
				empLang.setLangId((int) canLang.getLanguageId());
				empLang.setReadCompetency(canLang.getReadCompetency());
				empLang.setSpeakCompetency(canLang.getSpeakCompetency());
				empLang.setListenCompetency(canLang.getListenCompetency());
				empLang.setWriteCompetency(canLang.getWriteCompetency());
				
				empLang.setComments(canLang.getComment());
				empLang.setDateCreated(new Date());
				empLang.setDateModified(new Date());
				
				status = baseService.saveOrUpdate(empLang);
			}
		}
		
		// Copy Licenses.
		List<HreCandidateLicense> canLics = baseService.getPojos("candidateId", Compare.EQUAL, beanForm.getCanId(), null, null, -1, 0, HreCandidateLicense.class);
		if (canLics != null && canLics.size() > 0) {
			
			for (HreCandidateLicense canLic: canLics) {
				HreEmpLicense empLic = new HreEmpLicense();
				empLic.setEmpNumber(emp.getEmpNumber());
				empLic.setLicenseId(canLic.getLicenseId());
				empLic.setLicenseNo(canLic.getLicenseNo());
				empLic.setLicenseIssuedDate(canLic.getLicenseIssuedDate());
				empLic.setLicenseExpiryDate(canLic.getLicenseExpiryDate());
				empLic.setDateCreated(new Date());
				empLic.setDateModified(new Date());
				
				status = baseService.saveOrUpdate(empLic);
			}
		}
		
		// Copy Experiences.
		List<HreCandidateWorkExperience> canExps = baseService.getPojos("candidateId", Compare.EQUAL, beanForm.getCanId(), null, null, -1, 0, HreCandidateWorkExperience.class);
		if (canExps != null && canExps.size() > 0) {
			
			for (HreCandidateWorkExperience canExp: canExps) {
				HreEmpWorkExperience empExp = new HreEmpWorkExperience();
				empExp.setEmpNumber(emp.getEmpNumber());
				empExp.setEexpComments(canExp.getComments());
				empExp.setEexpEmployer(canExp.getEmployer());
				empExp.setEexpFromDate(canExp.getFromDate());
				empExp.setEexpInternal(canExp.getInternal());
				empExp.setEexpJobtit(canExp.getJobtit());
				empExp.setEexpToDate(canExp.getToDate());
				empExp.setDateCreated(new Date());
				empExp.setDateModified(new Date());
				
				status = baseService.saveOrUpdate(empExp);
			}
		}
		
		// Close the interview.
		HreJobInterview interview = baseService.getFirstPojo("id", Compare.EQUAL, beanForm.getIntId(), null, null, 0, HreJobInterview.class);
		if (interview != null) {
			interview.setStatus(3);
			baseService.saveOrUpdate(interview);
		}

		response.getWriter().write(StringConstants.POP_UP_CLOSE_SCRIPT);
		return null;
	}

	private void initFormBean(EmployForm beanForm) {
		beanForm.setAllUserRoles(ComboBoxInit.getAllUserRoles(true, false));
	}

	private String validateForm (EmployForm beanForm) {

		if (StringUtils.isBlank(beanForm.getPassword())) {
			return "Password cannot be blank!";
		}

		if(!beanForm.getPassword().equals(beanForm.getConfirmPassword())){
			return "Confirm password does not match!";
		}

		String verifyPassword = CommonUtils.verifyPassword(beanForm.getPassword());
		if (!StringConstants.BLANK.equals(verifyPassword)) {
			return verifyPassword;
		}

		return StringConstants.BLANK;
	}
	
	private void informHiringInformation (HreJobInterview tmp, HreJobCandidate tmpCan, HreUser tmpUser, String password) {
		
		if (tmp == null) {
			return;
		}
		
		HreJobVacancy tmpVac = baseService.getFirstPojo("id", Compare.EQUAL, tmp.getVacancyId(), HreJobVacancy.class);
		if (tmpVac == null) {
			return;
		}

		String message = "Congratulations " + tmpCan.getLastName();
		if (!"".equals(tmpCan.getMiddleName())) {
			message += " " + tmpCan.getMiddleName();
		}
		message += " " + tmpCan.getFirstName() + "!\n\n";
		message += "The human resource department of Telsoft Joint Stock company kindly informs you that you have been hired to the position " + tmpVac.getName() + ".";

		if (tmpUser != null) {
			message += " From now on, you can access the company web site for human resource (http://mw.xalo.vn/HREntry) as the username \"" + tmpUser.getUserName() + "\", and password \"" + password + "\".";
			message += " We strongly recommend that you should change the password at the first time you log in to the system.";
		}
		
		message += "\n\nThe human resource department will inform you other necessary information as soon as posible!";
		
		message += "\n\nThanks and best regards!";
		message += "\nHuman Resource Department - Telsoft JSC.";
		
		emailSender.sendMail(new String[]{tmpCan.getEmail()}, "Employment Information - Human Resource Department - Telsoft JSC.", message, false);
	}
}
